<template>
  <div class="container">
    <!-- 导航栏 -->
    <van-sticky>
      <van-nav-bar :title="hotelInfo.name" left-arrow @click-left="onPageBackClick"/>
    </van-sticky>

    <div class="content">
        <!-- 入住时间 -->
        <div class="booking-date-wrapper">
          <div class="booking-date">
            {{ checkInDateText }} - {{ checkOutDateText }}，共{{ bookingDays }}晚
          </div>
          <div class="room-type">
            <div class="main-info">
              <span class="right-divider">{{ roomType.name }}</span>
              <span>{{ roomType.currentPrice }}<sub>元/晚</sub></span>
            </div>
            <div class="more-info">
              <span class="right-divider">{{ roomType.size }}m<sup>2</sup></span>
              <span class="right-divider">{{ roomType.bed }}床</span>
              <span>{{ roomType.window }}</span>
            </div>
          </div>
        </div>

      <!-- 订房信息 -->
      <div class="booking-info">
        <!-- 表单 -->
        <div class="form-container">
          <van-form>
            <van-cell-group inset :border="false">
              <van-cell title="请填写入住人信息"></van-cell>
              <van-field required
                         v-model="formData.familyName"
                         name="username"
                         label="姓"
                         placeholder="请输入姓"
                         :rules="[{ required: true, message: '' }]"
              />
              <van-field required
                         v-model="formData.givenName"
                         name="username"
                         label="名"
                         placeholder="请输入名"
                         :rules="[{ required: true, message: '' }]"
              />
              <van-field name="radio" label="性别" required>
                <template #input>
                  <van-radio-group v-model="formData.gender" direction="horizontal">
                    <van-radio :name="1">男</van-radio>
                    <van-radio :name="0">女</van-radio>
                  </van-radio-group>
                </template>
              </van-field>
              <van-field required
                         v-model="formData.phoneNumber"
                         name="username"
                         label="手机号码"
                         placeholder="请输入手机号码"
                         :rules="[{ required: true, message: '' }]"
              />
            </van-cell-group>
          </van-form>

          <div class="tips">
            温馨提示：我们将收集您的姓名、联系方式、所选酒店名称以及入住与退房时间，用于实现您的酒店预订与入住服务。
          </div>

          <div class="tips warn">
            系统提示：当前系统并未实现支付功能，预订成功即视为支付成功，关于支付功能的实现，可参见后续项目。
          </div>
        </div>
      </div>
    </div>
    <!-- 提交栏 -->
    <van-submit-bar :price="roomType.currentPrice * bookingDays * 100" button-text="立即预订" button-color="#7458b0" @submit="onSubmit" />
  </div>
</template>

<script>
export default {
  data() {
    return {
      hotelInfo: {
        name: '',
        bookingNumber: '',
        feedbackNumber: '',
        locationIntro: '',
        locationAddress: ''
      },
      roomType: {
        id: 0
      },
      checkInDate: new Date(),
      checkOutDate: new Date(),
      checkInDateText: '',
      checkOutDateText: '',
      bookingDays: 0,
      member: {
        id: 0,
        familyName: '',
        givenName: '',
        gender: 0,
        phoneNumber: ''
      },
      formData: {
        familyName: '',
        givenName: '',
        gender: 0,
        phoneNumber: ''
      }
    }
  },
  methods: {
    onPageBackClick() {
      this.$router.back();
    },
    loadMemberInfo() {
      let member = {
        id: 1,
        familyName: '周',
        givenName: '星星',
        gender: 1,
        phoneNumber: '13800000000'
      };
      this.member = member;
      this.formData = member;
    },
    loadRoomTypeInfo() {
      let roomTypeList = [
        { id: 1, image: require("@/assets/image/room-1.png"), name: '大床房', size: '20-25', bed: '1张2*1.8米', window: '部分有窗', tags: ['温馨', '智能'], originalPrice: 600, currentPrice: 520, isRunningLow: false, stock: 10 },
        { id: 2, image: require("@/assets/image/room-2.png"), name: '双床房', size: '25-30', bed: '2张1.2*2米', window: '全部有窗', tags: ['舒适', '家庭'], originalPrice: 700, currentPrice: 630, isRunningLow: true, stock: 0 },
        { id: 3, image: require("@/assets/image/room-3.png"), name: '豪华套房', size: '40-50', bed: '1张2.5*2米', window: '全景落地窗', tags: ['奢华', '景观'], originalPrice: 1200, currentPrice: 1000, isRunningLow: false, stock: 3 },
        { id: 4, image: require("@/assets/image/room-4.png"), name: '标准单人间', size: '15-20', bed: '1张1.2*2米', window: '部分有窗', tags: ['简洁', '商务'], originalPrice: 400, currentPrice: 360, isRunningLow: false, stock: 8 },
        { id: 5, image: require("@/assets/image/room-5.png"), name: '亲子主题房', size: '30-35', bed: '1张2*2米+1张1.2*1.8米', window: '全部有窗', tags: ['亲子', '趣味'], originalPrice: 800, currentPrice: 720, isRunningLow: true, stock: 2 },
        { id: 6, image: require("@/assets/image/room-6.png"), name: '情侣浪漫房', size: '18-22', bed: '1张2*1.8米', window: '无窗', tags: ['浪漫', '私密'], originalPrice: 550, currentPrice: 495, isRunningLow: false, stock: 7 },
        { id: 7, image: require("@/assets/image/room-7.png"), name: '行政楼层套房', size: '45-55', bed: '1张2.5*2米', window: '全景落地窗', tags: ['高端', '安静'], originalPrice: 1500, currentPrice: 1300, isRunningLow: false, stock: 4 },
        { id: 8, image: require("@/assets/image/room-8.png"), name: '三人家庭房', size: '30-35', bed: '2张1.5*2米', window: '全部有窗', tags: ['家庭', '宽敞'], originalPrice: 850, currentPrice: 760, isRunningLow: true, stock: 3 },
        { id: 9, image: require("@/assets/image/room-9.png"), name: '四人团体房', size: '40-45', bed: '4张1.2*2米', window: '全部有窗', tags: ['团体', '实惠'], originalPrice: 1000, currentPrice: 900, isRunningLow: false, stock: 6 },
        { id: 10, image: require("@/assets/image/room-10.png"), name: '海景房', size: '35-40', bed: '1张2*2米', window: '全景海景窗', tags: ['美景', '放松'], originalPrice: 1300, currentPrice: 1100, isRunningLow: true, stock: 1 }
      ];
      for (let i = 0; i < roomTypeList.length; i++) {
        if (roomTypeList[i].id == this.roomType.id) {
          this.roomType = roomTypeList[i];
          break;
        }
      }
    },
    weekDayFormatter(date) {
      return ['周日', '周一', '周二', '周三', '周四', '周五', '周六'][date.getDay()];
    },
    onSubmit(values) {
      console.log('submit', values);
      // 这里可以添加登录逻辑，例如发送请求到后端
      alert('登录成功！用户名：' + values.username);
    }
  },
  created() {
    let roomTypeId = this.$route.query.roomTypeId;
    if (!roomTypeId) {
      this.$dialog.alert({
        title: '错误',
        message: '非法参数：' + roomTypeId,
      }).then(() => {
        this.$router.push('/');
      })
    } else {
      this.roomType.id = roomTypeId;
    }
  },
  mounted() {
    let hotelInfoString = localStorage.getItem('hotelInfo');
    if (hotelInfoString) {
      this.hotelInfo = JSON.parse(hotelInfoString);
    } else {
      this.$dialog.alert({
        title: '错误',
        message: '无法加载酒店数据，请返回！',
      }).then(() => {
        this.$router.push('/');
      })
    }

    let checkInDateString = localStorage.getItem('checkInDate');
    if (checkInDateString) {
      this.checkInDate = new Date(parseInt(checkInDateString));
      this.checkOutDate = new Date(parseInt(localStorage.getItem('checkOutDate')));
    } else {
      this.$dialog.alert({
        title: '错误',
        message: '无法加载入住时间数据，请返回！',
      }).then(() => {
        this.$router.push('/');
      })
    }

    let checkInWeekDayText = this.weekDayFormatter(this.checkInDate);
    let checkOutWeekDayText = this.weekDayFormatter(this.checkOutDate);

    let timestamp1 = this.checkInDate.getTime();
    let timestamp2 = this.checkOutDate.getTime();
    let differenceInMilliseconds = Math.abs(timestamp2 - timestamp1);
    let differenceInDays = Math.floor(differenceInMilliseconds / (1000 * 60 * 60 * 24));

    let checkOutDateText = `${checkOutWeekDayText}离店（共${differenceInDays}天）`;
    if (differenceInDays > 7) {
      checkOutDateText = `${differenceInDays}天后离店（${checkOutWeekDayText}）`;
    }

    this.checkInDateText = `${this.checkInDate.getMonth() + 1}月${this.checkInDate.getDate()}日（${checkInWeekDayText}）`;
    this.checkOutDateText = `${this.checkOutDate.getMonth() + 1}月${this.checkOutDate.getDate()}日（${checkOutWeekDayText}）`;
    this.bookingDays = differenceInDays;

    this.loadMemberInfo();
    this.loadRoomTypeInfo();
  }
}
</script>

<style scoped>
.container { max-width: 400px; background: #f6f6f6; height: 100vh; }
.van-submit-bar { max-width: 400px; }

.content { }

.booking-date-wrapper { background: #fff; padding: 10px 20px; }
.booking-date { font-size: 14px; padding: 8px 0; }
.room-type { padding: 8px 0; }
.room-type .main-info { font-size: 14px; }
.room-type .main-info sub { vertical-align: baseline; font-size: 0.6em; padding: 0 2px; }
.room-type .more-info { font-size: 11px; margin-top: 6px; color: #999; }
.right-divider { border-right: 1px solid #e1e1e1; padding-right: 10px; margin-right: 10px; }
.right-divider:last-child { border-right: none; }

.form-container { margin-top: 20px; }

.tips { padding: 16px 20px 0 20px; font-size: 11px; color: #999; line-height: 20px; }
.warn { color: #e62e2f; }
</style>